package hedron.dialog;

import static hedron.i18n.Internationalization._;
import hedron.Application;
import hedron.db.model.Contact;
import hedron.db.model.Stock;
import hedron.db.model.StoreName;
import hedron.db.model.StoredStock;
import hedron.editor.StoreEditor;
import java.util.Calendar;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;

public class StoredStockDialog extends AbstractDialog {

	private static final String STOCK_BUTTON_TEXT = _("Dialog.StoredStock.PickStock");
	private static final String CONTACT_BUTTON_TEXT = _("Dialog.StoredStock.PickContact");

	StoreName currentStore;
	DateTime date;
	Button contactButton;
	Button stockButton;
	Spinner quantity;
	Spinner buyPrice;
	Spinner sellPrice;
	Combo metric;

	Contact selectedContact;
	Stock selectedStock;
	StoreEditor storeEditor;

	public StoredStockDialog(Shell parentShell, StoreEditor storeEditor, StoreName currentStore) {
		super(parentShell);
		if (currentStore == null) {
			throw new IllegalArgumentException("currentStore may not be null");
		}
		this.currentStore = currentStore;
		this.storeEditor = storeEditor;
		selectedContact = null;
		selectedStock = null;
	}

	@Override
	public void create() {
		super.create();
		setTitle(_("Dialog.StoredStock.Title") + " " + currentStore.STORE_NAME);
		setMessage(_("Dialog.StoredStock.Message"), 0);
	}

	@Override
	protected void okPressed() {
		if (selectedContact == null) {
			setMessage(_("Dialog.StoredStock.Warn.Supplier"), 2);
			return;
		}
		if (selectedStock == null) {
			setMessage(_("Dialog.StoredStock.Warn.Stock"), 2);
			return;
		}
		int qty;
		try {
			String str = quantity.getText();
			qty = Integer.parseInt(str, 10);
			if (qty <= 0) {
				setMessage(_("Dialog.StoredStock.Warn.Quantity"), 2);
				return;
			}
		} catch (Exception e) {
			setMessage(_("Dialog.StoredStock.Err.Quantity"), 2);
			return;
		}
		double buyPriceValue;
		try {
			String str = buyPrice.getText();
			buyPriceValue = Double.parseDouble(str);
			if (buyPriceValue <= 0) {
				setMessage(_("Dialog.StoredStock.Warn.Price.Buy"), 2);
				return;
			}
		} catch (Exception e) {
			setMessage(_("Dialog.StoredStock.Err.Quantity"), 2);
			return;
		}
		double sellPriceValue;
		try {
			String str = sellPrice.getText();
			sellPriceValue = Double.parseDouble(str);
			if (sellPriceValue <= 0) {
				setMessage(_("Dialog.StoredStock.Warn.Price.Sell"), 2);
				return;
			}
		} catch (Exception e) {
			setMessage(_("Dialog.StoredStock.Err.Price.Sell"), 2);
			return;
		}
		String metricStr = metric.getText();

		try {

			StoredStock storedStock = new StoredStock();
			storedStock.STORE_ID = currentStore.getID();
			storedStock.STOCK_ID = selectedStock.getID();
			storedStock.CUSTOMER_ID = selectedContact.getID();
			storedStock.PRICE_BUY = buyPriceValue;
			storedStock.PRICE_SELL = sellPriceValue;
			storedStock.QTY = qty;
			storedStock.METRIC = metricStr;
			Calendar calendar = Calendar.getInstance();
			calendar.clear();
			calendar.set(date.getYear(), date.getMonth(), date.getDay(), 0, 0, 0);
			storedStock.DELIVERY_DATE = calendar.getTime();
			storedStock.store();

			final StringBuffer message = new StringBuffer();
			message.append(selectedStock.STOCK_NAME);
			message.append(" x").append(qty);
			message.append(' ').append(metricStr);
			message.append(" [ ").append(buyPriceValue);
			message.append(" , ").append(sellPriceValue);
			message.append("] успешно добавена");
			setMessage(message.toString(), 0);

			{
				selectedStock = null;
				contactButton.setText(CONTACT_BUTTON_TEXT);
				Font font = contactButton.getFont();
				FontData[] fontData = font.getFontData();
				fontData[0].setStyle(0);
				contactButton.setFont(new Font(contactButton.getDisplay(), fontData[0]));
			}

			{
				selectedContact = null;
				stockButton.setText(STOCK_BUTTON_TEXT);
				Font font = stockButton.getFont();
				FontData[] fontData = font.getFontData();
				fontData[0].setStyle(0);
				stockButton.setFont(new Font(stockButton.getDisplay(), fontData[0]));
			}


			quantity.setSelection(1);
			buyPrice.setSelection(0);
			sellPrice.setSelection(0);

			storeEditor.refresh();

		} catch (Exception e) {
			setMessage(e.getMessage(), 2);
		}
	}

	@Override
	void createContent(Composite parent) {

		final Composite grid = new Composite(parent, 0);
		grid.setLayoutData(new GridData(GridData.FILL_BOTH));

		{// set parent layout
			grid.setLayout(new GridLayout(1, false));

			final GridData gd = new GridData(GridData.FILL_BOTH);
			gd.widthHint = 500;
			grid.setLayoutData(gd);
		}

		{
			Composite area = new Composite(grid, 0);
			area.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			area.setLayout(new GridLayout(3, false));

			{// date
				final Label label = new Label(area, 0);
				label.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false));
				label.setText(_("Dialog.StoredStock.Label.Date"));

				final DateTime dateTime = new DateTime(area, SWT.DATE | SWT.BORDER);
				final GridData gd = new GridData(GridData.BEGINNING, GridData.CENTER, false, false);
				gd.heightHint = 20;
				gd.horizontalSpan = 2;
				dateTime.setLayoutData(gd);
				// dateTime.setText("");
				date = dateTime;
			}

			{// user
				final Label label = new Label(area, 0);
				label.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false));
				label.setText(_("Dialog.StoredStock.Label.Contact"));

				final Button button = new Button(area, SWT.PUSH);
				button.setText(CONTACT_BUTTON_TEXT);
				GridData gdata = new GridData(GridData.FILL, GridData.CENTER, true, false);
				gdata.horizontalSpan = 2;
				button.setLayoutData(gdata);
				button.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent event) {
						PickContactDialog dialog = new PickContactDialog(StoredStockDialog.this.getShell(),
								_("Dialog.StoredStock.PickContact.Title"), _("Dialog.StoredStock.PickContact.Message"));
						if (dialog.open() == Window.OK) {
							selectedContact = dialog.selectedContact;
							contactButton.setText(selectedContact.C_NAME);
							Font font = contactButton.getFont();
							FontData[] fontData = font.getFontData();
							fontData[0].setStyle(SWT.BOLD);
							contactButton.setFont(new Font(contactButton.getDisplay(), fontData[0]));
						}
					}
				});
				contactButton = button;
			}

			{// product
				final Label label = new Label(area, 0);
				label.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false));
				label.setText(_("Dialog.StoredStock.Label.Stock"));

				final Button button = new Button(area, SWT.PUSH);
				button.setText(STOCK_BUTTON_TEXT);
				GridData gdata = new GridData(GridData.FILL, GridData.CENTER, true, false);
				gdata.horizontalSpan = 2;
				button.setLayoutData(gdata);
				button.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent event) {
						PickStockDialog dialog = new PickStockDialog(StoredStockDialog.this.getShell(),
								_("Dialog.StoredStock.PickStock.Title") + " " + currentStore.STORE_NAME,
								_("Dialog.StoredStock.PickStock.Message"));

						if (dialog.open() == Window.OK) {
							selectedStock = dialog.selectedStock;
							stockButton.setText(selectedStock.GROUP_NAME + " - " + selectedStock.STOCK_NAME);
							Font font = stockButton.getFont();
							FontData[] fontData = font.getFontData();
							fontData[0].setStyle(SWT.BOLD);
							stockButton.setFont(new Font(stockButton.getDisplay(), fontData[0]));
						}
					}
				});
				stockButton = button;
			}

			{// quantity
				final Label label = new Label(area, 0);
				label.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false));
				label.setText(_("Dialog.StoredStock.Label.Quantity"));

				final Spinner spinner = new Spinner(area, SWT.BORDER);
				spinner.setMinimum(1);
				spinner.setMaximum(Integer.MAX_VALUE);
				spinner.setIncrement(1);
				spinner.setSelection(1);
				GridData gdata = new GridData(GridData.BEGINNING, GridData.CENTER, false, false);
				gdata.widthHint = 100;
				gdata.heightHint = 16;
				spinner.setLayoutData(gdata);
				quantity = spinner;

				final Combo combo = new Combo(area, SWT.BORDER | SWT.READ_ONLY);
				String[] metrics = Application.STORES.getMetrics();
				combo.setItems(metrics);
				combo.select(0);
				gdata = new GridData(GridData.BEGINNING, GridData.CENTER, false, false);
				gdata.widthHint = 50;
				gdata.heightHint = 18;
				combo.setLayoutData(gdata);
				metric = combo;
			}

			{// Expense
				final Label label = new Label(area, 0);
				label.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false));
				label.setText(_("Dialog.StoredStock.Label.Price.Buy"));

				final Spinner spinner = new Spinner(area, SWT.BORDER);
				spinner.setDigits(4);
				spinner.setMinimum(0);
				spinner.setMaximum(Integer.MAX_VALUE);
				spinner.setIncrement(10000);
				spinner.setSelection(0);
				GridData gdata = new GridData(GridData.BEGINNING, GridData.CENTER, false, false);
				gdata.widthHint = 100;
				gdata.heightHint = 16;
				gdata.horizontalSpan = 2;
				spinner.setLayoutData(gdata);
				buyPrice = spinner;
			}

			{// Income
				final Label label = new Label(area, 0);
				label.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false));
				label.setText(_("Dialog.StoredStock.Label.Price.Sell"));

				final Spinner spinner = new Spinner(area, SWT.BORDER);
				spinner.setDigits(4);
				spinner.setMinimum(0);
				spinner.setMaximum(Integer.MAX_VALUE);
				spinner.setIncrement(10000);
				spinner.setSelection(0);
				GridData gdata = new GridData(GridData.BEGINNING, GridData.CENTER, false, false);
				gdata.widthHint = 100;
				gdata.heightHint = 16;
				spinner.setLayoutData(gdata);
				sellPrice = spinner;

				final Label label1 = new Label(area, 0);
				label1.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
			}
		}
	}

	@Override
	void createFooter(Composite parent) {
		((GridLayout) parent.getLayout()).numColumns = 1;
		Composite grid = new Composite(parent, 0);
		grid.setLayoutData(new GridData(GridData.FILL, GridData.END, true, false));

		{// set grid layout
			GridLayout layout = new GridLayout();
			layout.numColumns = 3;
			grid.setLayout(layout);
		}
		{// cell 1 - empty text
			Label label = new Label(grid, 0);
			label.setText("");
			GridData gdata = new GridData(GridData.FILL, GridData.END, true, false);
			gdata.heightHint = 20;
			label.setLayoutData(gdata);
			label.setFocus();
		}
		{// cancel
			Button button = new Button(grid, SWT.PUSH);
			button.setText(_("Dialog.StoredStock.Button.Close"));
			GridData gdata = new GridData(GridData.BEGINNING, GridData.END, false, false);
			gdata.heightHint = 20;
			gdata.widthHint = 100;
			button.setLayoutData(gdata);
			button.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent e) {
					setReturnCode(CANCEL);
					close();
				}
			});
		}
		{// ok
			Button button = new Button(grid, SWT.PUSH);
			button.setText(_("Dialog.StoredStock.Button.Add"));
			GridData gdata = new GridData(GridData.END, GridData.END, false, false);
			gdata.heightHint = 20;
			gdata.widthHint = 100;
			button.setLayoutData(gdata);
			button.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent event) {
					okPressed();
				}
			});
		}
	}
}
